package com.ruoyi.file.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.file.FileUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.file.domain.FileAttachmentInfo;
import com.ruoyi.file.service.IFileAttachmentInfoService;
import com.ruoyi.system.api.domain.SysFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

/**
 * 文件请求处理
 *
 * @author ruoyi
 * http://localhost:8084/upload  请求路径
 */
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

/*
    @Autowired
    private ISysFileService sysFileService;
*/

    @Autowired
    private IFileAttachmentInfoService fileAttachmentInfoService;

    @PostMapping("/upload")
    public R<SysFile> upload(@RequestPart(value = "file") MultipartFile file, @RequestParam("tableName") String tableName, @RequestParam("colName") String colName,
                             @RequestParam("associationId") String associationId, @RequestParam("watermark") String watermark) {
        try {
            // 上传并返回访问地址 , String tableName, String colName

            HashMap<String, Object> stringObjectHashMap = fileAttachmentInfoService.uploadAttachment(file, tableName, colName, associationId, watermark);
            FileAttachmentInfo vo = (FileAttachmentInfo) stringObjectHashMap.get("url");
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(SecurityUtils.getUsername()));
//            String url = vo.getId();
//            if (com.ruoyi.common.core.utils.StringUtils.isNotEmpty(url)) {
//                url = "https://data.lvlianhengsheng.com/dev-api/file/fileAttachmentInfo/viewImage?key=" + url;
//            }
            sysFile.setUrl((String) stringObjectHashMap.get("url"));
            return R.ok(sysFile);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }
}